using System;
using System.Linq;

namespace SiteRecord
{
    public class UserEngine : SecurityBase
    {

        public static void Crawl(Users user)
        {
           
            user.UserSites.ToList().ForEach(siteItem =>
            {
                CrawlEngine newEngine = new CrawlEngine();

                Records record = newEngine.Load(siteItem.Url);
                record.UserSiteID = siteItem.ID;
                siteItem.SiteName = newEngine.Title;

                AppendNewRecord(record);
            });

        }

        private static void AppendNewRecord(Records record)
        {

            var item = SiteRecordContext.Records.FirstOrDefault(p => p.ModifyDate == record.ModifyDate && p.UserSiteID == record.UserSiteID);

            if (item == null)
            {
                SiteRecordContext.Records.InsertOnSubmit(record);
            }
            else
            {
                item.RecordCount = record.RecordCount;
                item.RecordDate = record.RecordDate;
                item.SnapshotUrl = record.SnapshotUrl;
            }

            SiteRecordContext.SubmitChanges();
        }
    }
}
